#pragma once
#include<iostream>
#include<sys/epoll.h>
#include<cerrno>
#include<cstring>
#include"Err.hpp"
#include"Log.hpp"

const static int size = 128;
const static int defulatepfd = -1;
class Epoller
{
public:
    Epoller():epfd_(defulatepfd)
    {}
    ~Epoller()
    {
        if(epfd_ != defulatepfd) close(epfd_);
    }
public:
    void Creat()
    {
        epfd_ = epoll_create(size);
        if(epfd_ < 0)
        {
            LogMessage(FATAL, "epoll creat failed! code :%d strerror : %s", errno, strerror(errno));
            exit(EPOLL_CREAT_ERR);
        }

        LogMessage(NORMAL, "epoll creat success!");
    }

    //user ——> kernel
    bool AddEvent(int sock,uint32_t event)
    {
        struct epoll_event evt;
        evt.data.fd = sock;//事件对应的fd
        evt.events = event;

        int n = epoll_ctl(epfd_, EPOLL_CTL_ADD, sock, &evt);

        return n == 0 ;
    }

    //Kernel ——> user
    int Wait(struct epoll_event revs[],int num,int timeout)
    {
        int n = epoll_wait(epfd_,revs,num,timeout);
        return n;
    }


    bool Control(int sock,uint32_t event,int action)
    {
        int n = 0;
        if(action == EPOLL_CTL_MOD)
        {
            struct epoll_event ev;
            ev.events = event;
            ev.data.fd = sock; 

            n = epoll_ctl(epfd_,action,sock,&ev);
        }
        else if(action == EPOLL_CTL_DEL)
        {
            n = epoll_ctl(epfd_,action,sock,nullptr);
        }
        else 
        {
            n = -1;
        }
        return n == 0;
    }

    void Close()
    {
        if(epfd_ != defulatepfd)close(epfd_);
    }

private:
    int epfd_;
};
